package com.wm.yigongfang.service;

import com.wm.yigongfang.common.entity.BaseEntity;
import com.wm.yigongfang.common.jwt.JwtUtil;
import com.wm.yigongfang.dao.UserDao;
import com.wm.yigongfang.dto.req.WXLoginReq;
import com.wm.yigongfang.dto.res.WXLoginRes;
import com.wm.yigongfang.dto.res.WeixinRes;
import com.wm.yigongfang.entity.User;
import com.wm.yigongfang.utils.WXUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.rowset.serial.SerialException;
import java.util.Date;
import java.util.Random;

/**
 * @Author ZhangPeng
 * @Date 2024/3/8 14:49
 * @PackageName:com.wm.yigongfang.service
 * @ClassName: UserService
 * @Description: TODO
 */
@Service
public class UserService {
    @Resource
    private UserDao userDao;

    public WXLoginRes wxLogin(WXLoginReq req) throws SerialException {
        WXLoginRes res = new WXLoginRes();
        // 获取微信openid
        WeixinRes sessionInfo = WXUtil.getSessionInfo(req.getCode());
        User user = userDao.lambdaQuery().eq(User::getWxOpenid, sessionInfo.getOpenid()).eq(BaseEntity::getIsDelete, 0).one();
        if (user == null) {
            // 创建用户
            user = createUser(sessionInfo.getOpenid(), sessionInfo.getSession_key());
        }
        res.setUser(user);
        res.setToken(JwtUtil.createToken(user.getWxOpenid()));
        return res;
    }

    private User createUser(String openid, String session_key){
        User user = new User();
        user.setAvatar("https://niix-pro.oss-accelerate.aliyuncs.com/images/media/1709882718000");
        user.setName("好师傅"+generateRandomString(openid));
        user.setPoints(0);
        user.setWxOpenid(openid);
        user.setWxSessionKey(session_key);
        user.setId(0);
        user.setCreateAt(new Date());
        user.setUpdateAt(new Date());
        user.setIsDelete(0);
        userDao.save(user);
        return user;
    }

    private static String generateRandomString(String givenString) {
        // 初始化一个用于生成随机数的Random对象
        Random random = new Random();

        // 定义用于随机选择的字符集
        String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

        // 用于存储生成的随机字符
        StringBuilder sb = new StringBuilder(8);

        // 生成前5位随机字符
        for (int i = 0; i < 5; i++) {
            int randomIndex = random.nextInt(charSet.length());
            sb.append(charSet.charAt(randomIndex));
        }

        // 从给定字符串中提取最后3位并附加到StringBuilder
        sb.append(givenString.substring(givenString.length() - 3));

        // 将StringBuilder转换为String并返回
        return sb.toString();
    }
}
